<template>
  <ui-page class="container">
    <!-- table -->
    <ui-table v-bind="table.config" ref="table" class="content_container" :params="{tenantId: userInfo.tenantId}"
              @select-change="onSelectTableEntity">
      <!--   查询   -->
      <template v-slot:search-bar>
        <ui-table-select v-model="table.model.select" :reset="true">
          <ui-table-select-item name="name" label="租户名称" placeholder="请输入租户名称" show-label type="text"
                                :show-word-limit="false"/>
          <ui-table-select-item name="status" label="租户状态" placeholder="请选择租户状态" show-label type="select" :data="tenantStatus"
                                :show-word-limit="false"/>
        </ui-table-select>
      </template>
      <!--   操作   -->
      <template v-slot:tool-bar>
        <el-button type="primary" icon="el-icon-plus" @click="handleEntityCreate">新增</el-button>
        <!--        <el-button type="primary" icon="el-icon-plus" @click="handleEntityDelete">删除</el-button>-->
        <!--        <el-button type="primary" icon="el-icon-printer" @click="handleEntityExport">导出</el-button>-->
      </template>
      <ui-table-column prop="name" label="租户名称"/>
      <ui-table-column prop="logo" label="logo">
        <template v-slot:default="{row}">
          <div style="display: flex;justify-content: center">
            <img :src="row.logo" alt="" style="width: 40px;height: 40px;"/>
          </div>
        </template>
      </ui-table-column>
      <ui-table-column prop="description" label="简介"/>
      <ui-table-column prop="phone" label="电话"/>
      <ui-table-column prop="address" label="地址"/>
      <ui-table-column prop="url" label="网址"/>
      <ui-table-column prop="beginTime" label="生效时间"/>
      <ui-table-column prop="endTime" label="到期时间"/>
      <ui-table-column prop="statusText" label="租户状态">
        <template v-slot:default="{row}">
            <span :style="{color: row.statusText === '启用' ? 'green' : 'red'}">
              {{ row.statusText }}
            </span>
        </template>
      </ui-table-column>
      <ui-table-column type="action" :buttons="table.buttons" :resizable="false"/>
      <!--   分页   -->
      <template v-slot:footer-bar>
        <ui-table-pagination/>
      </template>
    </ui-table>
    <!-- form -->
    <ui-form-dialog ref="form" :title="form.title" :url="form.url" :loading="entityGetLoading" :beforeSubmit="beforeSubmit"
                    :visible.sync="form.visible" class="entity-form" @after-submit="afterFormSubmit">
      <ui-form-item label="ID" name="id" type="hidden"/>
      <ui-form-item name="name" label="租户名称" type="text" vtype="required"/>
      <el-form-item name="logo" label="logo：" :rules="rules.logo">
        <el-upload
            class="avatar-uploader"
            action="http://10.11.67.241:8080/Sys/SysTenant/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="imgUrl" :src="imgUrl" class="avatar"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <ui-form-item name="description" label="简介" type="textarea"/>
      <ui-form-item name="phone" label="电话" type="text"/>
      <ui-form-item name="address" label="地址" type="text"/>
      <ui-form-item name="url" label="网址" type="text"/>
      <ui-form-item name="beginTime" label="生效时间" type="date"/>
      <ui-form-item name="endTime" label="到期时间" type="date"/>
      <ui-form-item name="maxUser" label="最大用户数" type="text"/>
      <ui-form-item name="administrator" label="管理员ID" type="text"/>
      <ui-form-item name="status" label="租户状态" type="select" :data="tenantStatus" vtype="required"/>
    </ui-form-dialog>
  </ui-page>
</template>
<script>
import {mapState} from 'vuex';

const SysTenant = {
  API: {
    create: '/Sys/SysTenant/create',
    update: '/Sys/SysTenant/update',
    delete: '/Sys/SysTenant/delete',
    select: '/Sys/SysTenant/select',
    export: '/Sys/SysTenant/export',
    upload: '/Sys/SysTenant/upload',
    createList: '/Sys/SysTenant/createList',
    updateList: '/Sys/SysTenant/updateList',
    deleteList: '/Sys/SysTenant/deleteList',
    selectList: '/Sys/SysTenant/selectList',
    selectPage: '/Sys/SysTenant/selectPage',
  },
  data() {
    return {
      api: SysTenant.API,
      table: {
        config: {
          url: SysTenant.API.selectPage,
        },
        model: {
          select: {},
        },
        buttons: [
          () => ({text: '修改', handle: this.handleEntityUpdateRow}),
          (row) => ({text: '删除', handle: this.handleEntityDeleteRow, disabled: row.id === this.userInfo.id}),
        ],
      },
      form: {
        isCreate: true,
        title: '新增',
        url: SysTenant.API.create,
        visible: false,
        rules: {},
      },
      imgUrl: '',
      rules: {
        logo: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ]
      },
      tenantStatus: [{value: 1, label: '启用'}, {value: 2, label: '停用'}]
    };
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    onSelectTableEntity(selects) {
      if (selects.length <= 0) {
        return;
      }
      this.handleEntityUpdateRow(selects[selects.length - 1]);
    },
    handleEntityCreate() {
      this.form.isCreate = true;
      this.$refs.form.resetValues();
      this.imgUrl = ''
      this.form.title = '新增';
      this.form.url = this.api.create;
      this.form.visible = true;
    },
    handleEntityUpdate() {
      const sels = this.$refs.table.getSelection();
      if (sels.length !== 1) {
        this.$message.info('请选择要修改的数据');
        return;
      }
      this.handleEntityUpdateRow(sels[0]);
    },
    handleEntityDelete() {
      const sels = this.$refs.table.getSelection();
      if (sels.length <= 0) {
        this.$message.info('请选择要删除的数据');
        return;
      }
      this.deleteEntities(sels.map(item => item.id)).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    handleEntityUpdateRow(row) {
      this.form.isCreate = false;
      this.form.title = '修改';
      this.form.url = this.api.update;
      this.form.visible = true;

      this.selectEntity(row.id).then(({success, data}) => {
        if (!success) {
          this.form.visible = false;
          return;
        }
        console.log(data)
        this.imgUrl = data.logo
        this.$refs.form.resetValues(data);
      });
    },
    handleEntityDeleteRow(row) {
      this.deleteEntity(row.id).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    async handleEntityExport() {
      const loading = this.$loading({text: '数据加载中..'});
      const url = this.api.export;
      await this.$refs.table.exportEntity(url, '导出.xls');
      loading.close();
    },
    beforeSubmit (values) {
      Object.assign(values, {logo: this.imgUrl})
    },
    reloadTable() {
      this.$refs.table && this.$refs.table.reload();
    },
    afterFormSubmit({success}) {
      if (!success) {
        return;
      }
      this.form.visible = false;
      this.reloadTable();
    },
    handleAvatarSuccess(res, file) {
      // this.imgUrl = URL.createObjectURL(file.raw) // 生成本地连接
      this.imgUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPGorPNG) {
        this.$message.error('上传的图片只能是 JPG或者PNG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传的图片大小不能超过 5MB!');
      }
      console.log(isJPGorPNG && isLt5M)
      return isJPGorPNG && isLt5M;
    }
  },
};
export default SysTenant;
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
